﻿using MaterialDemo.DataEntity;
using MaterialDemo.DataEntity.Entities;
using MaterialDemo.IService.IPermission;
using MaterialDemo.Model.DepartmentDTO;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MaterialDemo.Service.Permission
{
    public class DepartmentService : IDepartmentService
    {

        #region 构造函数注入
        private readonly ILogger<DepartmentService> _logger;
        private readonly DbContext _dbContext;
        public DepartmentService(ILogger<DepartmentService> logger, DbContext dbcontext)
        {
            _logger = logger;
            _dbContext = dbcontext;
        }

        #endregion



        /// <summary>
        /// 获取所有部门信息
        /// </summary>
        public List<DepartmentOutput> GetList()
        {
            return (from a in _dbContext.Set<DepartmentInfo>()
                    join b in _dbContext.Set<UserInfo>() on a.LeaderId equals b.UserId into join_a
                    from c in join_a.DefaultIfEmpty()
                    select new DepartmentOutput
                    {
                        DepartmentId = a.DepartmentId,
                        DepartmentName = a.DepartmentName,
                        Id = a.Id,
                        LeaderId = a.LeaderId,
                        ParentId = a.ParentId,
                        LeaderName = c.UserName,

                    }).ToList();
        }

        /// <summary>
        /// 递归获取对应用户以及他所有上级领导的信息--并从上往下排列好
        /// </summary>
        /// <param name="userId"></param>
        public List<DepartmentParentOutput> GetReviewerMsg(string userId)
        {
            //查到对应用户信息
            UserInfo userEntity = _dbContext.Set<UserInfo>().Where(u => u.UserId == userId).FirstOrDefault();
            //查到对应用户的部门信息--只有一条记录（暂时只做一对一的关系，一个人只有一个部门，一个部门只有一个领导）
            List<DepartmentInfo> dpEntity = _dbContext.Set<DepartmentInfo>().Where(u => u.DepartmentId == userEntity.DepartmentId).ToList();
            List<DepartmentParentOutput> list = new List<DepartmentParentOutput>();
            GetParentBoss(ref list, dpEntity);
            return list;
        }
        /// <summary>
        /// 根据id查询
        /// </summary>
        public List<DepartmentOutput> LoadEntities(int id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        public List<DepartmentOutput> LoadPageEntities(int pageIndex, int pageSize, out int totalCount, string selectInfo)
        {
            IQueryable<DepartmentInfo> iquery;
            if (string.IsNullOrEmpty(selectInfo))
            {
                totalCount = _dbContext.Set<DepartmentInfo>().Count();
                iquery = _dbContext.Set<DepartmentInfo>().OrderBy(u => u.DepartmentId).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            else
            {
                totalCount = _dbContext.Set<DepartmentInfo>().Where(u => u.DepartmentName.Contains(selectInfo)).Count();
                iquery = _dbContext.Set<DepartmentInfo>().Where(u => u.DepartmentName.Contains(selectInfo)).OrderBy(u => u.DepartmentId).Skip((pageIndex - 1) * pageSize).Take(pageSize);
            }
            var linq = from a in iquery
                       join b in _dbContext.Set<UserInfo>() on a.LeaderId equals b.UserId into join_a
                       from c in join_a.DefaultIfEmpty()
                       join e in _dbContext.Set<DepartmentInfo>() on a.ParentId equals e.DepartmentId
                       select new DepartmentOutput
                       {
                           DepartmentId = a.DepartmentId,
                           DepartmentName = a.DepartmentName,
                           Id = a.Id,
                           LeaderId = a.LeaderId,
                           LeaderName = c.UserName,
                           ParentId = a.ParentId,
                           ParentIdName = e.DepartmentName,
                           AddTime = a.AddTime,
                       };
            return linq.ToList();
        }

        /// <summary>
        /// 使用递归获取所有部门领导的信息--适用于一个人只有一个部门，一个部门只有一个领导
        /// </summary>
        /// <param name="sonEntity"></param>
        /// <returns></returns>
        public void GetParentBoss(ref List<DepartmentParentOutput> list, List<DepartmentInfo> sonEntity)
        {
            DepartmentParentOutput parenEntity = new DepartmentParentOutput();

            //连表->获取本级别部门领导名字,并存起来
            parenEntity = (from a in sonEntity
                           join b in _dbContext.Set<UserInfo>() on a.LeaderId equals b.UserId into join_a
                           from c in join_a.DefaultIfEmpty()
                           select new DepartmentParentOutput
                           {
                               LeaderId = a.LeaderId,
                               LeaderName = c.UserName,
                           }).FirstOrDefault();
            list.Add(parenEntity);
            if (sonEntity[0].ParentId == sonEntity[0].DepartmentId)
            {
                //说明到最顶级
                return;
            }
            else
            {
                //查到他的上一级部门
                List<DepartmentInfo> parentList = _dbContext.Set<DepartmentInfo>().Where(u => u.DepartmentId == sonEntity[0].ParentId).ToList();
                GetParentBoss(ref list, parentList);
            }
        }


        #region 增删改

        /// <summary>
        /// 添加部门
        /// </summary>
        public int Add(DepartmentInput inputEntity)
        {
            DepartmentInfo entity = new DepartmentInfo
            {
                DepartmentId = inputEntity.DepartmentId,
                DepartmentName = inputEntity.DepartmentName,
                LeaderId = inputEntity.LeaderId,
                ParentId = inputEntity.ParentId,
                AddTime = DateTime.Now
            };
            _dbContext.Set<DepartmentInfo>().Add(entity);
            return _dbContext.SaveChanges();
        }
        /// <summary>
        /// 修改部门
        /// </summary>
        public int Update(DepartmentInput inputEntity)
        {
            DepartmentInfo entity = _dbContext.Set<DepartmentInfo>().Where(u => u.DepartmentId == inputEntity.DepartmentId).FirstOrDefault();
            if (entity != null)
            {
                entity.DepartmentId = inputEntity.DepartmentId;
                entity.DepartmentName = inputEntity.DepartmentName;
                entity.LeaderId = inputEntity.LeaderId;
                entity.ParentId = inputEntity.ParentId;
                entity.AddTime = DateTime.Now;
            };
            _dbContext.Set<DepartmentInfo>().Update(entity);
            return _dbContext.SaveChanges();
        }


        /// <summary>
        /// 删除部门
        /// </summary>
        public int Delete(DepartmentInput inputEntity)
        {
            DepartmentInfo entity = new DepartmentInfo
            {
                DepartmentId = inputEntity.DepartmentId,
                DepartmentName = inputEntity.DepartmentName,
                LeaderId = inputEntity.LeaderId,
                ParentId = inputEntity.ParentId,
                AddTime = DateTime.Now
            };
            _dbContext.Set<DepartmentInfo>().Remove(entity);
            return _dbContext.SaveChanges();
        }
        #endregion
    }

}
